<?php

class SiteController extends Controller
{
	public $layout='//layouts/column2';
	
	public function filters()
    {
        return array(
            'accessControl',
        );
    }
	
	public function accessRules()
    {
        return array(
            array('allow',
                'actions'=>array('login','remind'),
                'users'=>array('?'),
            ),
            array('allow',
                'users'=>array('@'),
            ),
            array('deny',
                'users'=>array('*'),
            ),
        );
   }
	
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	public function actionLogin()
	{
		$this->menu = $this->menu = array(
			array('label'=>'Logowanie', 'url'=>array('/site/login')),
			array('label'=>'Przypomnienie hasła', 'url'=>array('/site/remind')),
		);
		$model = new LoginForm;

		if(isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		if(isset($_POST['LoginForm']))
		{
			$model->attributes = $_POST['LoginForm'];
			if($model->validate() && $model->login()) {
				switch(Yii::app()->user->type) {
					case 1:
						$this->redirect($this->createUrl('/users/index'));
						break;
					case 2:
						$this->redirect($this->createUrl('/station/admin'));
						break;
					case 3:
						$this->redirect($this->createUrl('/calendar/index'));
						break;
					case 4:
						$this->redirect($this->createUrl('/calendar/index'));
						break;
					default:
						$this->redirect(Yii::app()->user->returnUrl);
						break;
				}
			}
		}
		$this->render('login',array('model'=>$model));
	}

	public function actionRemind()
	{
		$success = 0;
		$this->menu = $this->menu = array(
			array('label'=>'Logowanie', 'url'=>array('/site/login')),
			array('label'=>'Przypomnienie hasła', 'url'=>array('/site/remind')),
		);
		$model = new RemindForm;

		if(isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		if(isset($_POST['RemindForm']))
		{
			$model->attributes = $_POST['RemindForm'];
			if($model->validate() && $model->remind($this)) {
				$model->email = '';
				$success = 1;
			}
		}
		$this->render('remind',array('model'=>$model,'success'=>$success));
	}

	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}